<template>
  <div class="userMgr">
    <div class="user_btn_operate">
      <div class="operate_btn">
        <el-button type="primary" v-for="(btn,index) in btnList" :key="index" plain @click="btnAction(btn.btnFn)"
                   size="small">
          {{ btn.btnName }}
        </el-button>
      </div>
      <div class="operate_action"></div>
    </div>
    <div class="user_table">
      <vxe-grid
        border
        resizable
        class="user_table_vxe_grid"
        ref="user_table"
        height="auto"
        v-loading="loading"
        :checkbox-config="{checkMethod: checkMethod, trigger: 'row'}"
        :row-config="{isCurrent: true, isHover: true}"
        :columns="tableColumn"
        :data="tableData"
        @sort-change="sortChange"
        @cell-click="cellClick">
        <template #operate="{row}">
          <vxe-button type="text" size="mini" @click="editUser(row)" :disabled="row.is_action === 'false'">
            <i class="vxe-icon-edit"></i>
          </vxe-button>
        </template>
        <template #pager>
          <vxe-pager
            perfect
            :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
            :current-page.sync="tablePage.currentPage"
            :page-size.sync="tablePage.pageSize"
            :total="tablePage.total"
            :page-sizes="[15,20,50,100]"
            @page-change="handlePageChange">
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>
    <el-dialog :title="currentDialog === 'create' ? '添加用户' : '修改用户信息'" :before-close="resetUserForm"
               :visible.sync="dialogUserFormVisible"
               width="30%">
      <el-form :model="userForm" ref="userForm" :rules="userFormRules" size="small" label-width="50px">
        <el-form-item label="账号" prop="account">
          <el-input v-model="userForm.account" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="userForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="currentDialog === 'create'">
          <el-input v-model="userForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-radio-group v-model="userForm.role">
            <el-radio label="student">学生</el-radio>
            <el-radio label="teacher">教师</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogUserFormVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="dialogUserFormOk(currentDialog)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { httpRequest } from "@/untils/httpRequest";

export default {
  name: "UserMgr",
  data() {
    return {
      loading: false,
      btnList: [
        { btnName: "添加用户", btnFn: "addUser" },
        { btnName: "删除用户", btnFn: "deleteUser" },
        { btnName: "刷新", btnFn: "reFresh" }
      ],
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 15
      },
      sortCfg: {
        property: "",
        order: ""
      },
      tableColumn: [
        { type: "checkbox", width: 50 },
        { field: "id", title: "ID", sortable: true },
        { field: "name", title: "Name", sortable: true },
        { field: "account", title: "账户", sortable: true },
        { field: "role", title: "Role", sortable: true },
        { field: "createdAt", title: "创建时间", sortable: true },
        { field: "updatedAt", title: "最近修改时间", sortable: true },
        { title: "操作", align: "center", slots: { default: "operate" } }
      ],
      tableData: [],
      userForm: {
        account: "",
        name: "",
        password: "",
        role: "student"
      },
      userFormRules: {
        account: [
          { required: true, message: "请输入账户", trigger: "blur" }
        ],
        name: [
          { required: true, message: "请输入名称", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" }
        ]
      },
      currentDialog: "create",
      dialogUserFormVisible: false
    };
  },
  methods: {
    getUser() {
      let params = Object.assign(this.tablePage, this.sortCfg);
      return new Promise((resolve) => {
        this.loading = true;
        httpRequest("post", "/user/getUser", null, params, "proxy").then(res => {
          if (res && res.data.code === 200) {
            this.tableData = res.data.data.user;
            this.tablePage.total = res.data.data.tablePage.total;
            resolve();
          }
          this.loading = false;
        });
      });
    },
    checkMethod({ row }) {
      return row.is_action === "true";
    },
    handlePageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage;
      this.tablePage.pageSize = pageSize;
      this.getUser();
    },
    sortChange({ property, order }) {
      this.sortCfg = Object.assign({ property, order }, {});
      this.getUser();
    },
    btnAction(btnFn) {
      this[btnFn]();
    },
    getSelectRows() {
      return this.$refs["user_table"].getCheckboxRecords();
    },
    addUser() {
      this.resetUserForm();
      this.dialogUserFormVisible = true;
    },
    deleteUser() {
      let selectRows = this.getSelectRows();
      if (selectRows.length === 0) {
        this.$message.warning("至少选择一条数据");
      } else {
        return new Promise((resolve) => {
          let ids = selectRows.map((item) => {
            return item.id;
          });
          httpRequest("post", "/user/deleteUser", null, { ids }, "proxy").then(res => {
            if (res.data.code === 200) {
              this.$message.success(res.data.msg);
              this.getUser();
              this.dialogUserFormVisible = false;
              resolve();
            }
            this.loading = false;
          });
        });
      }
    },
    editUser(row) {
      this.resetUserForm();
      this.userForm = JSON.parse(JSON.stringify(row));
      this.currentDialog = "edit";
      this.dialogUserFormVisible = true;
    },
    reFresh() {
      this.getUser();
    },
    resetUserForm() {
      if (this.$refs["userForm"]) {
        this.$refs["userForm"].resetFields();
      }
      this.currentDialog = "create";
      this.userForm = {
        account: "",
        name: "",
        password: "",
        role: "student"
      };
      this.dialogUserFormVisible = false;
    },
    dialogUserFormOk(currentDialog) {
      if (currentDialog === "create") {
        this.$refs["userForm"].validate((valid) => {
          if (valid) {
            let params = this.userForm;
            return new Promise((resolve) => {
              httpRequest("post", "/user/addUser", null, params, "proxy").then(res => {
                if (res.data.code === 200) {
                  this.$message.success(res.data.msg);
                  this.getUser();
                  this.resetUserForm();
                  resolve();
                }
                this.loading = false;
              });
            });
          }
        });
      } else {
        this.$refs["userForm"].validate((valid) => {
          if (valid) {
            let params = this.userForm;
            return new Promise((resolve) => {
              httpRequest("post", "/user/editUser", null, params, "proxy").then(res => {
                if (res.data.code === 200) {
                  this.$message.success(res.data.msg);
                  this.getUser();
                  this.resetUserForm();
                  resolve();
                }
                this.loading = false;
              });
            });
          }
        });
      }
    },
    cellClick({ row }) {

    }
  },
  mounted() {
    this.getUser();
  }
};
</script>

<style scoped lang="less">
.userMgr {
  width: 100%;
  height: 100%;
  padding: 0 15px;
  overflow: auto;

  .user_btn_operate {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
  }

  .user_table {
    width: 100%;
    height: calc(100vh - 112px);
  }
}
</style>